package com.sunpy.niohttp.codec;

import com.sunpy.niohttp.model.SunpyRequest;

import java.io.*;
import java.nio.ByteBuffer;

public class HttpDecoder {

    /**
     * POST / HTTP/1.1
     * username: zhangsan
     * cache-control: no-cache
     * Postman-Token: 63dde61d-efbf-4aa7-9b7a-732f1c608603
     * Content-Type: text/plain
     * User-Agent: PostmanRuntime/7.1.1
     * Accept: **
     * Host:127.0.0.1:9999
     * accept-encoding:gzip,deflate
     * content-length:34
     * Connection:keep-alive
     *
     *{"level":5,"age":23,"name":"lisi"}
     */
    public SunpyRequest decodeHttp(ByteBuffer buffer) throws IOException {
        SunpyRequest request =new SunpyRequest();

        BufferedReader br =new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buffer.array())));
        // 第一行数据请求行
        String lineData =br.readLine();
        String[] lineArr = lineData.split(" ", 3);
        request.setMethod(lineArr[0]);
        request.setUri(lineArr[1]);
        request.setVersion(lineArr[2]);
        // 第二行数据请求头
        String headerData = br.readLine();
        while (headerData != null && !headerData.equals("")) {
            String[] headerArr = headerData.split(":", 2);
            request.getHeaders().put(headerArr[0], headerArr[1]);
            headerData = br.readLine();
        }
        // 第三行空行不解析，第四行请求体
        StringBuilder sb = new StringBuilder();
        String bodyData = br.readLine();
        while (bodyData != null && !bodyData.equals("")) {
            sb.append(bodyData);
            bodyData = br.readLine();
        }

        request.setBody(sb.toString());
        return request;
    }
}
